/**
 * Created by ZFL on 2018/1/30.
 */
/**
 * Created by ph on 2016/8/18.
 */
/** 全局插件 **/
$.extend({
    ajaxApi:function(){
        return "http://api.biz.nongtebest.com/";  //败家接口正式
    },
    wxApi:function () {
        return "http://h5bj.nongtebest.com/";  //败家h5正式
    },
    imgApi:function () {
    },
    /*2016-07-09  获取url参数值 */
    getPara:function(name,url){
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        if (url) {
            if (url.indexOf("?") != -1)
                url = url.split("?")[1];
        } else if (window.location.search.length > 1) {
            url = decodeURI(window.location.search.substr(1));
        } else {
            return '';
        }
        var r = url.match(reg);
        if (r != null) return unescape(r[2]); return '';
    },
    GetRequest:function(){
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for(var i = 0; i < strs.length; i ++) {
                theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    },
    /*2016-07-09 ajax请求*/
    ajaxHandler:function(ajaxObj){
        var visible = ajaxObj.visible || "show";
        var approve = ajaxObj.approve || false;
        var g={
            loading:function (text) {
                var _content = "";
                if(text) _content =text;
                if(visible=="show"){ //显示加载 loading
                    var loader = '<div class="loading-box"><div class="loading-bounce-box"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div><div class="loading-content">'+_content+'</div></div>';
                    if($(".loading-box").length<1){
                        $("body").append(loader);
                        $(".loading-box").addClass("open");
                    }else{
                        if(!$(".loading-box").hasClass("open")){
                            $(".loading-box").addClass("open");
                        }
                    }
                }
            },
            //隐藏进度条
            hideload:function () {
                if($(".loading-box").length>0){
                    var visibleTime =ajaxObj.visibleTime || 0; //毫秒
                    if(visibleTime>0){
                        setTimeout(function () {
                            $(".loading-box").removeClass("open");
                        },visibleTime)
                    }else{
                        $(".loading-box").removeClass("open");
                    }
                }
            },
            // 成功返回处理
            success:function (data, textStatus) {
                try {
                    if (data == undefined || data == '') {
                        g.hideload();
                        return;
                    }
                    var result;
                    if(data.code){
                        result=data;
                    }else{
                        result = JSON.parse(data);
                    }
                    if (ajaxObj.success){
                        ajaxObj.success(result,textStatus);
                    }
                    g.hideload();
                } catch (e) {
                    //g.toast("系统繁忙，请稍后再试！");
                    console.log(e.name+ e.message+ e.lineNumber);
                    setTimeout(function () {
                        g.hideload();
                    }, 2500);
                }
            },
            beforeSend:function(XMLHttpRequest) {
                if(approve){
                    //XMLHttpRequest.setRequestHeader("userToken","da5d1be1-cd10-4eb2-bfe9-70ccc98c8410");

                    if($.getStorage("userData")){
                        XMLHttpRequest.setRequestHeader("userToken",JSON.parse($.getStorage("userData")).token);

                    }else{
                        if($.getPara("appToken")){
                            XMLHttpRequest.setRequestHeader("userToken",$.getPara("appToken"));
                        }else if($.getStorage("appToken")){
                            XMLHttpRequest.setRequestHeader("userToken",$.getStorage("appToken"));
                        }
                    }
                }
            },
            // 失败返回处理
            error:function (e) {
                $.errorVue();
                $.delStorage("userData");
                $.delStorage("userData");
                $.delStorage("yg_wx");
                g.hideload();
                console.error(e);

            },
            // 提交动作
            submit:function () {
                var param = null;
                if (ajaxObj.model) {
                    if (typeof ajaxObj.model == "function") {
                        param = JSON.stringify(ajaxObj.model());
                    }else{
                        param ="{}";
                    }
                }else{
                    param ="{}";
                }
                var async =ajaxObj.async || "";
                var post = ajaxObj.type || "post";
                var dataType = ajaxObj.dataType || "json";
                var url;
                if(ajaxObj.apiUrl){
                    url = ""+ajaxObj.apiUrl+""+ajaxObj.api+"";
                }else{
                    url = $.ajaxApi()+""+ajaxObj.api+"";
                }
                var option = {
                    type:post,
                    async: false,
                    contentType: "application/json;charset=utf-8",
                    dataType: dataType,
                    url: url,
                    data:''+param+'',
                    beforeSend:g.beforeSend,
                    complete:g.hideload,
                    success: g.success,
                    error: g.error
                };
                var _ajax = $.ajax(option);
                return _ajax;
            }
        };
        //执行
        g.loading();
        return g.submit();
    },
    /*
     * 显示加载
     */
    errorVue:function () {
        var html ='<div class="system-error"></div> <div class="system-error-box"> <img class="img" src="../src/images/system_error.png"> <div class="text">啊哦，出错了啦~</div> </div>';
        $('body').append(html);
    },
    showScrollLoad:function(){
        var loader = '<div class="loading-box-bottom"> <div class="loading-bounce-box"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div></div>';
        if($(".loading-box-bottom").length<1){
            $("body").append(loader);
            $(".loading-box-bottom").addClass("open");
        }else{
            if(!$(".loading-box-bottom").hasClass("open")){
                $(".loading-box-bottom").addClass("open");
            }
        }
    },
    /*
     * 掩藏加载
     */
    hideScrollLoad:function(time){
        if($(".loading-box-bottom").length>0){
            if(time){
                setTimeout(function () {
                    $(".loading-box-bottom").removeClass("open");
                },visibleTime);
            }else{
                $(".loading-box-bottom").removeClass("open");
            }
        }
    },
    /*
     * 存储值localstorage
     */
    setStorage:function (name,value){
        if(window.localStorage.getItem(name)){
            window.localStorage.setItem(name,JSON.stringify(value));
        }else{
            window.localStorage[name] =JSON.stringify(value);
        }
    },
    /*
     * 读取localstorage
     */
    getStorage:function (name){
        if(window.localStorage.getItem(name))
            return window.localStorage.getItem(name);
        else
            return null;
    },
    /*
     * 删除localstorage
     */
    delStorage:function (name) {
        if(window.localStorage.getItem(name))
            return window.localStorage.removeItem(name);
    },
    /*
     * 是否是微信浏览器
     */
    isWX:function(){
        var ua = navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i)=="micromessenger") {
            return true;
        } else {
            return false;
        }
    },
    /*
     * penghe 2016-07-09 微信获取Code
     */
    GetWXCode:function(UrlHosts){
        $.delStorage("userData");
        $.delStorage("yd_wx");
        $.delStorage("userData");
        var obj = {};

        if(com_obj.mallStoreId){
            obj.mallStoreId  = com_obj.mallStoreId;
        }
        obj.payType  =3;
        if(com_obj.type){
            obj.type  = com_obj.type;
        }else{
            obj.type  = 0;
        }
        $.setStorage("goodsType",obj.type);
        $.ajaxHandler({
                model: function () {
                    console.log(obj)
                    return obj;
                },
                visibleTime: 100,
                dataType: "json",
                api: 'yg_baijiaplatform/wecha/getAppId',
                success: function (result) {
                    //console.log(result);
                    if (result.code == 10000) {
                        var data = result.data;
                        var urlhost = (UrlHosts)?UrlHosts:window.location.href;

                        var wxUrl ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='+data.appId+'&redirect_uri='+encodeURIComponent(urlhost)+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';




                        window.location.href = wxUrl;


                    }else {
                        $.toast('AppId异常','text');
                    }

                }
            }
        );

    },
    /*
     * ph 2016-07-09 通过网页授权获取用户基本信息
     */
    GetAccessToken:function () {
            var obj={};
            if($.getPara("code")){
                obj.code=$.getPara("code");
            }
            if(com_obj.mallStoreId){
                obj.storeId  =  com_obj.mallStoreId;
            }else{
                obj.storeId= $.getStorage('mallStoreId');
                com_obj.mallStoreId=$.getStorage('mallStoreId');
            }
            obj.type=2;

            //if(com_obj.type){
            //    obj.type  = com_obj.type;
            //}else if($.getStorage("goodsType")){
            //    obj.type = parseInt($.getStorage("goodsType"));
            //}else{
            //    obj.type  = 0;
            //}
            $.ajaxHandler({
                model:function(){
                    console.log(obj);
                    return obj;
                },
                visible:"hide",
                visibleTime:0,
                dataType:"json",
                api:"yg_baijiaplatform/unDefinedUser/authorization",
                success:function (result) {
                    if(result.code==10000){
                        var data = result.data;
                        //if(data.accessToken){
                            var obj ={};
                            obj.access_token = data.accessToken;
                            obj.openid  = data.openId;
                            obj.refresh_token =data.refreshToken;
                            obj.nickname  = data.nickName;
                            obj.picture=data.picture;
                            obj.sex = data.sex;
                            obj.province =data.province;
                            obj.userId=data.userId;
                            obj.userName=data.userName;
                            obj.money=data.money;
                            obj.token=data.token;
                            window.localStorage.setItem("userOpenid",data.openId);

                            $.setStorage("userData",obj);

                            //注册用户
                        com_obj.userId = JSON.parse($.getStorage('userData')).userId;
                                PageInit();
                    }
                    else{
                        YDUI.dialog.toast(result.message,'error',1000)
                    }
                }
            });


    },
    /*
     * ph 检验授权凭证（access_token）是否有效 并刷新access_token
     */
    VerifyAccessToken:function () {
        var obj ={};
        if(com_obj.mallStoreId){
            obj.storeId  = com_obj.mallStoreId;
        }
        //else if($.getPara("mallStoreId")!=''){
        //    obj.storeId  = $.getPara("mallStoreId");
        //    com_obj.mallStoreId  = $.getPara("mallStoreId");
        //}else if($.getStorage("mallStoreId")){
        //    obj.storeId = $.getStorage("mallStoreId");
        //    com_obj.mallStoreId  = $.getStorage("mallStoreId");
        //}
        if($.getStorage("goodsType")){
            obj.type  = $.getStorage("goodsType");
        }else if(com_obj.type){
            obj.type  = com_obj.type;
        }else{
            obj.type = 0;
        }
        var token = JSON.parse(window.localStorage.getItem('userData'));
        if(token){
            $.ajaxHandler({
                model:function () {
                    obj.accessToken = token.access_token;
                    obj.openId = token.openid;
                    obj.refreshToken = token.refresh_token;
                    return obj;
                },
                visible:"hide",
                visibleTime:0,
                dataType:"JSON",
                api:"yg_baijiaplatform/undefinedUser/geiPengHeYong",
                success:function (result) {
                    if(result.code==10000){
                        var data =result.data;
                        if(data.access_token){
                            var obj ={};
                            obj.access_token = data.access_token;
                            obj.openid  = data.openid;
                            obj.refresh_token =data.refresh_token;
                            obj.nickname  = token.nickname;
                            obj.headimgurl  = token.headimgurl;
                            obj.sex = token.sex;
                            obj.province =token.province;

                            $.setStorage("userData",obj);
                            com_obj.userId = JSON.parse(window.localStorage.getItem('userData')).userId;
                            //更新分享用户ID
                            //if($.getPara('talentId')!=''){
                            //    obj.talentId  = $.getPara('talentId');//分享人id
                            //    $.setStorage("talentId",parseFloat($.getPara("talentId")));
                            //    com_obj.talentId = parseFloat($.getPara('talentId'));
                            //}else if($.getPara('userTalentId')!=''){
                            //    obj.talentId  = $.getPara('userTalentId');//分享人id
                            //    $.setStorage("talentId",parseFloat($.getPara("userTalentId")));
                            //    com_obj.talentId = parseFloat($.getPara('userTalentId'));
                            //}else if($.getStorage("talentId")){
                            //    com_obj.talentId  = parseFloat($.getStorage("talentId"));
                            //}
                            //开始执行
                            com_obj.userId = JSON.parse($.getStorage('userData')).userId;
                            PageInit();
                        }else{
                            var Request = new Object();
                            Request = $.GetRequest();
                            var code = Request["code"];
                            if(code && code!=""){
                                //alert("code获取成功");
                                //通过code换取网页授权access_token
                                $.GetAccessToken();
                            }else{
                                $.GetWXCode();
                            }
                        }
                    }else{
                        //校验失败
                        $.GetWXCode();
                    }
                }
            });
        }else{
            //token不存在 重新获取code
            $.GetWXCode();
        }
    },



});

function  verifyInfo() {
    var token = JSON.parse(window.localStorage.getItem('userData'));
    if(token){
        $.ajaxHandler({
            model:function () {
                var obj ={};
                obj.nickName = '宝宝';
                if(token.sex==0){
                    obj.sex = 1;//默认男士
                }else{
                    obj.sex = token.sex;
                }
                obj.undefinedId = token.openid;
                obj.urlHeader = token.headimgurl;
                return obj;
            },
            visible:"hide",
            visibleTime:0,
            dataType:"json",
            api:"yg_baijiaplatform/undefinedUser/getUndefinedUserByUndefinedId",
            success:function (result) {
                if(result.code==10000){
                    var data = result.data;
                    var userD  = data.userInfo;
                    var _obj  ={};
                    _obj.nickName  = data.nickName;
                    if(data.picture.toString().indexOf('http')>-1){
                        _obj.picture  = data.picture;
                    }else{
                        _obj.picture  = $.imgApi()+''+data.picture;
                    }
                    _obj.userName  = data.userName;
                    _obj.userId  = userD.userId;
                    _obj.persionId  =userD.persionId;
                    _obj.recommendFrom  =data.recommendFrom;
                    _obj.money  = data.money;
                    _obj.sex  = userD.sex;
                    _obj.token = data.token;
                    alert('888')
                    $.setStorage("userData",_obj);
                    com_obj.userId = userD.userId;
                    //开始执行
                    PageInit();
                }else if(result.code==20000){
                    YDUI.dialog.toast('获取用户异常',1000);
                }else{
                    YDUI.dialog.toast('获取用户异常',1000);
                }
            }
        });
    }else{
        //access_token 不存在
    }
}
/** 对象级别插件 **/
(function($){
    $.fn.extend({
        test:function(content){
            console.log("测试输出内容:"+content);
            //访问     $("a").test();
        }
    });
})(jQuery);
/*保存信息*/
var saveInfo = function(data,text,httpUrl) {
    var _obj  ={};
    //console.log(data);
    _obj.nickName  = data.nickName;
    if(data.picture.toString().indexOf('http')>-1){
        _obj.picture  = data.picture;
    }else if(data.picture!=''){
        _obj.picture  =data.picture;
    }else{
        //默认头像
        _obj.picture  ='../images/user/user_img.png';
    }
    _obj.userName  = data.userName;
    _obj.userId  = data.userId;
    _obj.level = data.level;
    _obj.token = data.token;
    _obj.persionId=data.persionId;
    _obj.recommendFrom  =data.recommendFrom;
    _obj.money  = data.money;
    _obj.sex  = data.sex;
    if(data.openId){
        _obj.openId = data.openId;
        window.localStorage.setItem("userOpenid",data.openId);
    }else{
        _obj.openId=$.getStorage("userOpenid")
    }
    $.setStorage("userData",_obj);
    com_obj.userId = data.userId;//用户Id
    console.log(com_obj.userId)
    com_obj.roleId = data.roleId;//用户角色Id

};

/*public 函数*/

// ----------------------------------
// 减运算，避免数据相除小数点后产生多位数和计算精度损失。
// ---------------------------------
function subtractNumber(arg1,arg2){
    return (arg1*1000-arg2*1000)/1000;//防止丢失精度
}
// ----------------------------------
// 乘运算，避免数据相除小数点后产生多位数和计算精度损失。
// ---------------------------------
function SubNumber(arg1,arg2){
    return (arg1*1000)*(arg2*1000)/1000000;//防止丢失精度
}
// ----------------------------------
// 相加运算，避免数据相除小数点后产生多位数和计算精度损失。
// ---------------------------------
function andNumber(arg1,arg2){
    return ((arg1*1000)+(arg2*1000))/1000;//防止丢失精度
}
// ----------------------------------
// 除，避免数据相除小数点后产生多位数和计算精度损失。
// ---------------------------------
function divideNumber(arg1,arg2){
    return ((arg1*1000)/(arg2*1000));//防止丢失精度
}
// ----------------------------------
// 函数：取当前日期(若有参数n，则推后或者提前几天)
// ----------------------------------
function getCurrentDay(n, basicDate) {
    var today = basicDate || new Date();
    if (n) {
        today = new Date(today.valueOf() + n * 24 * 60 * 60 * 1000);
    }
    var day = today.getDate();

    var month = today.getMonth() + 1;
    var year = today.getFullYear();
    if (month < 10) {
        var strMonth = "0" + month;
    }
    else {
        strMonth = month;
    }
    if (day < 10) {
        var strDay = "0" + day;
    } else {
        strDay = day;
    }
    var date = year + "-" + strMonth + "-" + strDay;

    return date;
}

// ----------------------------------
// 函数：取当前月份(若有参数n，则推后或者提前几月)
// ----------------------------------
function getCurrentMonth(n) {
    var today = new Date();
    if (!n) n = 0;
    var month = today.getMonth() + 1 + n;
    var year = today.getFullYear();
    if (month < 10) {
        var strMonth = "0" + month;
    }
    else {
        strMonth = month;
    }
    var date = year + "-" + strMonth;

    return date;
}

//--------------------------------------------
//函数：获得当前的日期和时间（格式：2009-06-12 12:09:06）
//-------------------------------------------------
function CurentTime() {
    var now = new Date();
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日

    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分
    var ms = now.getSeconds();     //秒
    var clock = year + "-";

    if (month < 10)
        clock += "0";

    clock += month + "-";

    if (day < 10)
        clock += "0";

    clock += day + " ";

    if (hh < 10) { clock += "0"; }
    clock += hh + ":";
    if (mm < 10) { clock += '0'; }
    clock += mm + ":";
    if (ms < 10) { clock += '0'; }
    clock += ms;
    return (clock);
}
// ----------------------------------
// 金额格式化函数：s:金额 n:保留几位小数
// ----------------------------------
function fmoney(s, n) {
    n = n >= 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    //是否是负数
    var prestr = '';
    if (s.substring(0, 1) == "-") {
        s = s.substring(1, s.length);
        prestr = '-';
    }
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
    t = "";
    for (i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }

    if (n == 0)
        return prestr + t.split("").reverse().join("");
    else
        return prestr + t.split("").reverse().join("") + "." + r;
}
// ----------------------------------
// 还原格式化金额
// ----------------------------------
function rmoney(s) {
    return parseFloat(s.replace(/[^\d\.-]/g, ""));
}
// ----------------------------------
// 根据指定日期计算与指定日期的天数
// ---------------------------------
function diffDays(s1){
    s1 = s1.replace(/-/g, "/");
    s1 = new Date(s1);
    s2 = new Date();
    var days= s1.getTime() - s2.getTime();
    var times = parseInt(Math.abs(days / (1000 * 60 * 60 * 24)));
    return times;
}
//截取金额后两位
function  fmoneyStr(money) {
    if(money.toString().indexOf(".")>-1){
        var length= money.toString().split(".")[1].length;
        if(length>2){
            var length1=money.toString().split(".")[0].length+3;
            return parseFloat(money.toString().substr(0,length1));
        }else{
            return parseFloat(money);
        }
    }else{
        return parseFloat(money);
    }
}
// ----------------------------------
// 微信网页授权  OAuth2.0
// ---------------------------------
function wxAccredit(){
    //if($.getStorage("userData")){
    //    //用户存在
    //    com_obj.userId = JSON.parse($.getStorage("userData")).userId;
    //}
    //if(window.localStorage.getItem('userData')){
    //    //校验token是否有效
    //    $.VerifyAccessToken();
    //}else{

        var code = $.getPara('code');
        if(code && code!=""){
            //alert("code获取成功");
            //通过code换取网页授权access_token
            $.GetAccessToken();
        }else{
            $.GetWXCode();
        }
    //}
    //

}
/*public 入口*/
var com_obj={};
$(function () {
    var url=window.location.href;
    if(url.indexOf('codeTopay')<0){
        //非一码支付页面
        if($.getPara('mallStoreId')){
            com_obj.mallStoreId= $.getPara('mallStoreId');    //店铺id
            window.localStorage.setItem("mallStoreId",$.getPara('mallStoreId'));
        }
        if($.getPara('userTalentId')){
            com_obj.talentId= $.getPara('userTalentId') ;     //分享人id
            window.localStorage.setItem("userTalentId",$.getPara('userTalentId'));
        }

        //$init = new  jsEnter();


        //每次点开链接    都需要清除用户本地的userData    和花生云店不同   这是因为不同的店铺的同一用户的信息是不同的
        if(!window.sessionStorage["delData"]){
            $.delStorage('userData');
            window.sessionStorage["delData"] ='1';

        }
        if($.getStorage('userData')){
            com_obj.userId = JSON.parse($.getStorage('userData')).userId;
            console.log(com_obj.userId)
            PageInit();
        }else{
            wxAccredit();
        }
    }else{
        //一码支付页面
        PageInit();
    }


    //if($.getStorage('userData')){
    //    com_obj.userId = JSON.parse($.getStorage('userData')).userId;
    //    //$init = new  jsEnter();
    //    PageInit();
    //}

});